package com.sunyard.pcc.common.shiro.impl;

import com.sunyard.pcc.common.bo.SysUserCacheBO;
import com.sunyard.pcc.common.constant.ErrorCodeEnum;
import com.sunyard.pcc.common.exception.PccCommonException;
import com.sunyard.pcc.common.shiro.UserSaveService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @Author: Hewei
 * @Description: 用户存储接口实现类， 实现redis存储
 * @Date: Created in 15:42 2018/3/12
 */
@Slf4j
@Component(value = "redisCache")
public class RedisUserSaveServiceImpl implements UserSaveService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public SysUserCacheBO getCacheUser() throws PccCommonException {
        String key = getKeyOfSession(getSession());
        return (SysUserCacheBO) redisTemplate.opsForValue().get(key);
    }

    @Override
    public void saveUser(SysUserCacheBO user) throws PccCommonException {
        Optional.ofNullable(user)
                .orElseThrow(() -> new PccCommonException(ErrorCodeEnum.PARAM_EMPTY));

        String key = getKeyOfSession(getSession());
        redisTemplate.opsForValue().set(key, user);
    }

    @Override
    public void removeUser() throws PccCommonException {
        String key = getKeyOfSession(getSession());
        redisTemplate.delete(key);
    }


    /**
     * 获取用户redis存储的key
     * @param session
     * @return
     */
    private static String getKeyOfSession(Session session){
        return "sessionId: " + session.getId().toString();
    }
}
